package com.atguigu.gmall.pms.service.impl;

import com.atguigu.gmall.pms.entity.*;
import com.atguigu.gmall.pms.feign.GmallSmsClient;
import com.atguigu.gmall.pms.mapper.SkuMapper;
import com.atguigu.gmall.pms.mapper.SpuDescMapper;
import com.atguigu.gmall.pms.service.SkuAttrValueService;
import com.atguigu.gmall.pms.service.SkuImagesService;
import com.atguigu.gmall.pms.service.SpuAttrValueService;

import com.atguigu.gmall.pms.vo.SkuVo;
import com.atguigu.gmall.pms.vo.SpuAttrValueVo;
import com.atguigu.gmall.pms.vo.SpuVo;
import com.atguigu.gmall.sms.vo.SkuSaleVo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.gmall.common.bean.PageResultVo;
import com.atguigu.gmall.common.bean.PageParamVo;

import com.atguigu.gmall.pms.mapper.SpuMapper;
import com.atguigu.gmall.pms.service.SpuService;
import org.springframework.util.CollectionUtils;


@Service("spuService")
public class SpuServiceImpl extends ServiceImpl<SpuMapper, SpuEntity> implements SpuService {
    @Autowired
    private SpuDescMapper descMapper;
    @Autowired
    private SpuAttrValueService spuAttrValueService;
    @Autowired
    private SkuMapper skuMapper;
    @Autowired
    private SkuImagesService imagesService;
    @Autowired
    private SkuAttrValueService saleAttrValueService;
    @Autowired
    private GmallSmsClient smsClient;



    @Override
    public PageResultVo queryPage(PageParamVo paramVo) {
        IPage<SpuEntity> page = this.page(
                paramVo.getPage(),
                new QueryWrapper<SpuEntity>()
        );

        return new PageResultVo(page);
    }

    @Override
    public PageResultVo querySpusByCidAndPage(Long cid, PageParamVo paramVo) {
        QueryWrapper<SpuEntity> wrapper = new QueryWrapper<>();

        //如果查询条件id是0，则查询全站，也就是说id不为0的时候，才需要添加条件
        if(cid !=0 ){
            wrapper.eq("category_id",cid);
        }
        //获取搜索的关键字
        String key = paramVo.getKey();
        if (StringUtils.isNotBlank(key)){
            wrapper.and(t-> t.eq("id",key).or().like("name",key));


        }
        IPage<SpuEntity> page = this.page(
                paramVo.getPage(),
                wrapper
        );

        return new PageResultVo(page);

    }

    @Override
    public void bigSave(SpuVo spu) {
        // 1.保存spu相关的信息
        //1.1保存pms_spu表
        spu.setCreateTime(new Date());
        spu.setUpdateTime(spu.getCreateTime());
        this.save(spu);
        Long spuId = spu.getId();
        //1.2保存pms_spu_desc表
        List<String> spuImages = spu.getSpuImages();

        if (!CollectionUtils.isEmpty(spuImages)){
            SpuDescEntity spuDescEntity = new SpuDescEntity();
            spuDescEntity.setSpuId(spuId);
            spuDescEntity.setDecript(StringUtils.join(spuImages,","));
            this.descMapper.insert(spuDescEntity);
        }

        //1.3保存pms_spu_attr_value表
        List<SpuAttrValueVo> baseAttrs = spu.getBaseAttrs();
         //把Vo转换成entity集合
    if (!CollectionUtils.isEmpty(baseAttrs)) {
        List<SpuAttrValueEntity>  spuAttrValueEntities=baseAttrs.stream().map(spuAttrValueVo -> {
            SpuAttrValueEntity spuAttrValueEntity = new SpuAttrValueEntity();
            BeanUtils.copyProperties(spuAttrValueVo,spuAttrValueEntity);
            return spuAttrValueEntity;
        }).collect(Collectors.toList());
        this.spuAttrValueService.saveBatch(spuAttrValueEntities);
    }






        // 2.保存sku相关的信息
        // 2.保存sku相关信息
        List<SkuVo> skus = spu.getSkus();
        if (CollectionUtils.isEmpty(skus)){
            return;
        }
      skus.forEach(skuVo -> {

          //2.1保存pms_sku表
          skuVo.setSpuId(spuId);
          skuVo.setBrandId(spu.getBrandId());
          skuVo.setCategoryId(spu.getCategoryId());
          //获取图片列表  第一个图片作为默认图片
          List<String> images =skuVo.getImages();
          if (!CollectionUtils.isEmpty(images)){
              skuVo.setDefaultImage(StringUtils.isBlank(skuVo.getDefaultImage())?images.get(0):skuVo.getDefaultImage());

          }
          skuMapper.insert(skuVo);
          Long skuId = skuVo.getId();

          //2.2保存pms_sku_desc表
          if (!CollectionUtils.isEmpty(images)){



              this.imagesService.saveBatch(    images.stream().map(
                      image ->{
                          SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                          skuImagesEntity.setId(skuId);
                          skuImagesEntity.setUrl(image);
                          skuImagesEntity.setDefaultStatus(StringUtils.equals(skuVo.getDefaultImage(),image)?1:0);
                          return skuImagesEntity;
                      }
              ).collect(Collectors.toList()));

          }
          //2.3保存pms_sku_attr_value表
          List<SkuAttrValueEntity> saleAttrs = skuVo.getSaleAttrs();
          saleAttrs.forEach(skuAttrValueEntity -> {
              skuAttrValueEntity.setAttrId(skuId);
          });
          this.saleAttrValueService.saveBatch(saleAttrs);

          // 3.保存营销相关的信息
          SkuSaleVo skuSaleVo = new SkuSaleVo();
          BeanUtils.copyProperties(skuVo,skuSaleVo);
          skuSaleVo.setSkuId(skuId);

          this.smsClient.saveSales(skuSaleVo);

          //3.1保存pms_sku_bounds 积分优惠信息表
          //3.2保存pms_sku_full_reduction满减信息表
          //3.3保存pms_sku_ladder打折信息表



      });






    }





}